package com.taotao.wechat.business;

import com.rop.client.CompositeResponse;
import com.taotao.admin.MyRopClient;
import com.taotao.rop.database.domain.RopAppSecret;
import com.taotao.rop.database.domain.WechatAccesstoken;
import com.taotao.rop.response.BaseResponse;
import org.apache.log4j.Logger;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

public class Accesstoken {
    private Logger logger = Logger.getLogger(Accesstoken.class);
    public String appId;
    private String urlFormat = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    public Accesstoken(String appId){
        this.appId = appId;
    }

    public static void main(String[] args){
        Accesstoken accesstoken = new Accesstoken("wx77ae5030ce533f0c");
        accesstoken.getAccesstoken();
    }

    public String getAccesstoken(){
        String accesstoken = "";
        WechatAccesstoken condition = new WechatAccesstoken();
        condition.setAppId(this.appId);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "accesstoken.list", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> data = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (data != null && data.size() > 0) {
                    LinkedHashMap<String, Object> dataMap = data.get(0);
                    //获取数据库中存储的更新时间，同时转化为当前时区时间，相差14个小时
                    Long updateTime = Long.parseLong(dataMap.get("updateTime").toString()) - 14 * 3600 * 1000;
                    Long now = new Date().getTime();
                    //如果超过3600秒未更新
                    logger.info("token更新时间：" + (now - updateTime));
                    if (now - updateTime >= 3600 * 1000 || now - updateTime < 0) {
                        accesstoken = updateAccesstoken();
                    } else {
                        accesstoken = dataMap.get("accessToken").toString();
                    }
                } else {
                    accesstoken = updateAccesstoken();
                }
            }
        }
        System.out.println("accesstoken:"+accesstoken);
        return accesstoken;
    }

    public String updateAccesstoken(){
        String accesstoken = "";
        String appSecret = "";

        RopAppSecret condition = new RopAppSecret();
        condition.setAppId(this.appId);
        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient("").buildClientRequest()
                .post(condition, BaseResponse.class, "appSecret.listAll", "1.0");
        if (response.isSuccessful()) {
            BaseResponse baseResponse = response.getSuccessResponse();
            if (baseResponse.getSuccess()) {
                List<LinkedHashMap<String, Object>> data = (List<LinkedHashMap<String, Object>>) baseResponse.getData();
                if (data != null && data.size() > 0) {
                    LinkedHashMap<String, Object> dataMap = data.get(0);
                    appSecret = dataMap.get("appSecret").toString();
                }
            }
        }

        if (appSecret.length() > 0) {
            RestTemplate restTemplate = new RestTemplate();
            LinkedHashMap<String, Object> result = restTemplate.getForObject(String.format(urlFormat, this.appId, appSecret), LinkedHashMap.class);
            if (result.get("access_token") != null) {
                accesstoken = result.get("access_token").toString();

                WechatAccesstoken wechatAccesstoken = new WechatAccesstoken();
                wechatAccesstoken.setAppId(this.appId);
                CompositeResponse<BaseResponse> countResp = MyRopClient.getRopClient("").buildClientRequest()
                        .post(wechatAccesstoken, BaseResponse.class, "accesstoken.count", "1.0");
                if (countResp.isSuccessful()) {
                    BaseResponse baseResponse = countResp.getSuccessResponse();
                    if (baseResponse.getSuccess()) {
                        wechatAccesstoken.setAccessToken(accesstoken);
                        wechatAccesstoken.setUpdateTime(new Date());
                        Long count = Long.parseLong(baseResponse.getData().toString());
                        if (count > 0) {
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(wechatAccesstoken, BaseResponse.class, "accesstoken.update", "1.0");
                        } else {
                            MyRopClient.getRopClient("").buildClientRequest()
                                    .post(wechatAccesstoken, BaseResponse.class, "accesstoken.insert", "1.0");
                        }
                    }
                }
            }
        }

        return accesstoken;
    }
}
